package lk.icta.core.service.impl;

import lk.icta.common.ELandRuntimeException;
import lk.icta.common.ErrorCodes;
import lk.icta.core.dao.MortgageDAO;
import lk.icta.core.entity.Mortgage;
import lk.icta.core.service.MortgageManagementService;
import lk.icta.user.common.Permission;
import lk.icta.user.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Duminda Dharmakeerthi
 */
public class MortgageManagementServiceImpl implements MortgageManagementService {

    private static final Logger logger = LoggerFactory.getLogger(MortgageManagementServiceImpl.class);
    private final MortgageDAO mortgageDAO;

    public MortgageManagementServiceImpl(MortgageDAO mortgageDAO) {
        this.mortgageDAO = mortgageDAO;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void addMortgage(Mortgage mortgage, User user) {
        logger.debug("Adding a mortgage {}", mortgage.getNameOfBank());
        if (!user.isAuthorized(Permission.INITIAL_LAND_DATA_ENTRY) || !user.isAuthorized(Permission.DETAIL_LAND_DATA_ENTRY)) {
            handleELandRuntimeException(user.getUsername() + " doesn't have permission to add an Alienation", ErrorCodes.UNAUTHORIZED_ACCESS);
        } else {
            mortgageDAO.addMortgage(mortgage, user);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void updateMortgage(Mortgage mortgage, User user) {
        if (user.isAuthorized(Permission.INITIAL_LAND_DATA_MODIFICATION) || user.isAuthorized(Permission.DETAIL_LAND_DATA_MODIFICATION)) {
            logger.debug("Updating mortgage details");
            mortgageDAO.updateMortgage(mortgage, user);
        } else {
            logger.debug("Doesn't have permission");
            handleELandRuntimeException(user.getUsername() + " doesn't have permission to update mortgage details", ErrorCodes.UNAUTHORIZED_ACCESS);
        }
    }

    private void handleELandRuntimeException(String message, int code) {
        logger.error(message);
        throw new ELandRuntimeException(message, code);
    }
}
